package com.tanguy.user.ui.me.activity.account

import android.app.Activity
import android.content.Intent
import android.widget.EditText
import android.widget.TextView
import com.tanguy.user.Const
import com.tanguy.user.R
import com.tanguy.user.base.ImmersionTitleActivity
import com.tanguy.user.net.http.HttpManager
import com.tanguy.user.utlis.extend.*
import org.jetbrains.anko.find
import org.jetbrains.anko.startActivityForResult

/**
 * 验证手机
 * type 1.登陆
 *      2.修改密码
 */

class PhoneActivity : ImmersionTitleActivity() {
    var type = 1
    override fun setContentViewRes(): Int = R.layout.activity_phone
    lateinit var mTvCaptcha: TextView
    lateinit var phone: EditText
    override fun initView() {
        super.initView()
        title = "验证手机"
        mTvCaptcha = find(R.id.tv_get_captcha)
        phone = find(R.id.et_phone)
        type = intent.getIntExtra(Const.IntentCode.VERIFY_PHONE, 1)
    }

    override fun initEvent() {
        super.initEvent()
        apply {
            click(R.id.btn_next) {
                val phone1 = getEditTextString(R.id.et_phone)
                val captcha = getEditTextString(R.id.et_captcha)
                if (!checkPhoneNumber(phone1)) return@click
                if (!checkCaptcha(captcha)) return@click
                HttpManager.yzCode(phone1, 2, getEditTextString(R.id.et_captcha))
                        .requestSucceed(this@PhoneActivity) {
                            if (type == 1) {
                                startActivityForResult<SetPasswordActivity>(Const.RequestCode.LOGIN_REQUEST, "type" to 1, "phone" to phone1)
                            } else {
                                startActivityForResult<SetPasswordActivity>(Const.RequestCode.LOGIN_REQUEST, "type" to 2)
                            }

                        }
            }
        }
        click(mTvCaptcha) { getCaptcha() }

    }

    private fun getCaptcha() {
        val phone = getEditTextString(phone)
        if (!checkPhoneNumber(phone)) return

        HttpManager.sendSmsCode(phone, 2)
                .requestSucceed(this) {
                    // 获取验证码
                    compositeDisposable.add(captchaCountDownTimer { finish, msg ->
                        mTvCaptcha.isClickable = finish
                        mTvCaptcha.text = msg
                    })
                }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && requestCode == Const.RequestCode.LOGIN_REQUEST) {
            setResult(Activity.RESULT_OK)
            finish()
        }
    }
}
